package org.easy.eao.spring;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.apache.commons.lang.reflect.MethodUtils;
import org.easy.eao.Action;
import org.easy.eao.annotations.Target;
import org.easy.eao.exception.ExecuteException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

/**
 * 代理目标方法执行器
 * @author Frank
 */
public class TargetAction implements Action<Target>, BeanFactoryAware {

	private Object target;
	
	protected Target annotation;
	protected Method method;
	protected Class<?> clz;

	@Override
	public void initialize(Annotation annotation, Method method, Class<?> clz) {
		this.annotation = (Target) annotation;
		this.clz = clz;
		this.target = beanFactory.getBean(this.annotation.value());
		this.method = MethodUtils.getMatchingAccessibleMethod(target.getClass(), method.getName(), method.getParameterTypes());
	}

	@Override
	public Class<Target> getAnnotationClass() {
		return Target.class;
	}
	
	@Override
	public Object execute(Object[] parameters) {
		try {
			return method.invoke(target, parameters);
		} catch (Exception e) {
			throw new ExecuteException(e);
		}
	}

	private BeanFactory beanFactory;
	
	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

}
